package com.daydayup.learn;


import lombok.Getter;

import java.util.Random;
import java.util.concurrent.CountDownLatch;


/**
 * 三个销售卖SU7，求3个销售团队总体销售额,每个销售自己的销量分开统计
 */
public class ThreadLocalDemoV2 {

    public static void main(String[] args) throws InterruptedException {
        SU7 su7 = new SU7();
        CountDownLatch countDownLatch = new CountDownLatch(3);
        for (int i = 0; i < 3; i++) {
            new Thread(() -> {
                try{
                    for (int j = 0; j < new Random().nextInt(3)+1; j++) {
                        su7.saleTotal();// 本门店销售总和统计全部加
                        su7.salePersonal();//各个销售独立的销售额,只和自己有关
                    }
                    System.out.println(Thread.currentThread().getName()+"号销售卖出:"+su7.salePersonal.get());
                } finally {
                    countDownLatch.countDown();
                    su7.salePersonal.remove();// 清理线程本地资源,防止影响后续业务或者内存泄漏
                }

            },String.valueOf(i)).start();
        }
        countDownLatch.await();
        System.out.println(Thread.currentThread().getName()+"\t销售总额:"+su7.getSaleTotal());
    }

    private static class SU7{
        @Getter
        private int saleTotal;
        public synchronized void saleTotal() {
            saleTotal++;
        }

        // ThreadLocal 求3个销售的各自独立的个体销售额,不参加总和计算
//        ThreadLocal<Integer> salePersonal = new ThreadLocal<>(){
//            @Override
//            protected Integer initialValue() {
//                return 0;
//            }
//        };
        ThreadLocal<Integer> salePersonal = ThreadLocal.withInitial(() -> 0);

        public void salePersonal(){
            salePersonal.set(1+salePersonal.get());
        }

    }
}
